<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>
    <title><%= title %></title>
    <link rel="icon" href="favicon.ico"/>
    <link rel="stylesheet" href="css/main.css"/>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="js/socket.io-stream.js"></script>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/my/repo.data.js"></script>
    <script type="text/javascript">
    var socket = io();
    var bUpdatingTips = false;

    function submitForm(formId, submitButtonId) {
        $('#tipsTable')[0] && ($('#tipsTable')[0].style.display = 'none');
        var customRepoEle = $('#customrepo1');
        if (formId == 'pastesome') {
            customRepoEle = $('#customrepo2');
        }
        var formEle = $('#' + formId);
        var btnEle = $('#' + submitButtonId);
        btnEle.disabled = 'disabled';
        btnEle.value = '正在提取，请稍等！';
        $('#msgcontainer').empty();
        $('#messages')[0].style.display = 'block';
        // formEle.submit();
        var d = {
            action: formEle.attr('action')
        };
        var t = formEle.serializeArray();
        $.each(t, function () {
            if (this.name in d) {
                d[this.name] = d[this.name] + ',' + this.value;
            } else {
                d[this.name] = this.value;
            }
            // 特殊处理：自定义仓库URL
            if (this.name == 'repo' && this.value == 'custom') {
                d['repo'] = customRepoEle.val();
            }
        });
        if (formEle.attr('action') == '/upload') {
            var file = $('#modfile')[0].files[0];
            var stream = ss.createStream();
            ss(socket).emit('upload file', stream, {name: file.name, size: file.size});
            ss.createBlobReadStream(file).pipe(stream);
            d['file'] = {};
            d['file']['path'] = file.name;
        }
        socket.emit('add request', JSON.stringify(d));
        // alert(JSON.stringify(d));
    }

    socket.on('chat message', function (msg) {
        // appendMessage('[INFO]' + msg);
        appendMessage(msg);
    });

    socket.on('error message', function (msg) {
        appendMessage('[ERROR]' + msg);
    });

    function appendMessage(msg) {
        msg = msg.replace(/\r\n/g, '\n');
        var lines = msg.split('\n');
        lines.forEach(line => {
            if (line.substring(0, 8) == '[FINISH]' || line.substring(0, 10) == '[FINISH#2]') {
                if (line.substring(0, 8) == '[FINISH]') {
                    $('#msgcontainer').append('<a href="/download?id=' + line.substring(8) + '">下载结果文件（一小时内有效）</a>');
                } else {
                    $('#msgcontainer').append('<a href="/download?id=' + line.substring(10) + '">下载结果文件#2（一小时内有效）</a>');
                }
                $('#msgcontainer').append($('<div>').addClass('finishMsg').html('成功完成'));
             } else if (line.substring(0, 7) == '[ERROR]') {
                $('#msgcontainer').append($('<div>').addClass('errMsg').html(line));
            } else {
                $('#msgcontainer').append($('<div>').html(line));
            }
        });
        document.getElementById('msg_end').scrollIntoView();
        // $('msg_end').focus();
    }

    function showMessages() {
        $('#messages')[0].style.display = 'block';
    }

    function clearMessages() {
        $('#messages')[0].style.display = 'none';
    }

    function showHelp() {
        var msg = '本工具用于快速从golang代码仓库提取源码包和相关的依赖包（含mod文件），并自动同步到内网仓库中。<br/>' + 
            '如果知道需要的源码包的发布URL和版本信息，可以直接提取；否则，需要自行通过github.com等网站查找。';
        var html = "<div class='closebtn'><a href='javascript:void(0)' onclick='clearHelp()'>[关闭]</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>";
        $('body').append($('<div id="helpDiv">').html(html + msg));
    }

    function clearHelp() {
        $('#helpDiv').remove();
    }

    function clearComment(curObj) {
        if (bUpdatingTips) {
            return;
        }
        var curText = curObj.value;
        var newText = curText.replace(/<!--.+?-->/, '');

        bUpdatingTips = true;
        curObj.value = newText;
        bUpdatingTips = false;
    }

    function getTips() {
        if (bUpdatingTips) {
            return;
        }
        var urlObj = $('#url')[0];
        var urlStr = urlObj.value;
        if (urlStr.length < 4) {
            return;
        }
        var url = '/search/keyword?q=' + urlStr;
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(jsonObj) {
                console.log(jsonObj);
                if (jsonObj && jsonObj.length) {
                    var datas = jsonObj;
                    if (datas.length > 0) {
                        if ($('#tipsTable').length > 0) {
                            $('#tipsTable').remove();
                        }
                        var tbodyEle = $('<tbody>').append($('<tr>')
                            .append($('<th>').text('URL'))
                            .append($('<th>').text('Version'))
                            .append($('<th>').text('操作')));
                        var tableEle = $('<table id="tipsTable">').addClass('tipsTable').append(tbodyEle);
                            datas.forEach(data => {
                            var trEle = $('<tr>');
                            trEle.append($('<td>').text(data.url));
                            trEle.append($('<td>').text(data.version));
                            trEle.append($('<td>').html('<a class="smlLnk" href="javascript:void(0)"' + 
                                ' onclick="writeUrl(\'' + data.url + '\',\'' + 
                                data.version + '\')">选中</a>'));
                            tbodyEle.append(trEle);
                        });
                        tableEle.css('left', urlObj.getBoundingClientRect().right + 2);
                        tableEle.css('top', urlObj.getBoundingClientRect().top);
                        $('body').append(tableEle);
                    }
                }
            }
        });
    }

    function gotoWeb() {
        var urlObj = $('#url')[0];
        var urlStr = urlObj.value;
        window.open('https://pkg.go.dev/search?q=' + urlStr);
    }

    function writeUrl(url, version) {
        bUpdatingTips = true;
        $('#url').val(url);
        $('#version').val(version);
        $('#tipsTable').remove();
        bUpdatingTips = false;
    }

    window.onload = function () {
        var defaultVal = 'github.com/xxxxxxxx/yyyyyyyy v0.0.0\n' + 
            'github.com/xxxxxxxx/yyyyyyyy v0.0.0\n' + 
            'github.com/xxxxxxxx/yyyyyyyy v0.0.0';
        $('#urllist').val(defaultVal);
    }
    </script>
</head>
<body>
    <center>
    <h1>欢迎使用 <%= title %></h1>
    <br/>
    目前，有以下几种不同的提取方式，请根据自己的需要选择使用。&nbsp;&nbsp;<a class='smlLnk' href='javascript:void(0)' onclick='showHelp()'>帮助</a>
    <br/>
    <h3>1、上传go.mod文件方式</h3>
    <div>
        <form id='editfile' method='post' action='/upload' enctype='multipart/form-data'>
            <table><tbody>
                <tr><td style="width:100px;">选择文件：</td><td style="width:480px;"><input name="modfile" id='modfile' type='file' /></td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitFile' value='上传文件并开始提取' onclick="submitForm('editfile','submitFile')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    <br/>
    <h3>2、指定单个包的信息提取方式</h3>
    <div>
        <form id='editsingle' method='post' action='/uploadsingle'>
            <table><tbody>
                <tr><td style="width:100px;">Repo：</td><td style="width:480px;"><span>https://mirrors.aliyun.com/goproxy/</span></td></tr>
                <tr><td>URL：</td><td><input name="url" id='url' type='text' size="30" /><input type="button" value="搜索" onclick="getTips()" />
                <input type="button" value="转到" onclick="gotoWeb()" /></td></tr>
                <tr><td>version：</td><td><input name="version" id='version' type='text' size="30" /></td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitSingle' value='开始提取' onclick="submitForm('editsingle','submitSingle')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    <br/>
    <h3>3、粘贴一段go.mod中的依赖模块列表的提取方式</h3>
    <div>
        <form id='pastesome' method='post' action='/uploadsome'>
            <table><tbody>
                <tr><td style="width:100px;">Repo：</td><td style="width:480px;"><span>https://mirrors.aliyun.com/goproxy/</span></td></tr>
                <tr><td>模块列表：</td><td><textarea name="urllist" id='urllist' cols="55" rows="6" oninput="clearComment(this)"></textarea></td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitSome' value='开始提取' onclick="submitForm('pastesome','submitSome')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    </center>
    <div id='messages'>
        <div class='closebtn'><a href="javascript:void(0)" onclick="clearMessages()">[关闭]</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>
        <div id='msgcontainer'></div>
        <div id='msg_end'></div>
    </div>
    <div id='operatebar'><a href="javascript:void(0)" onclick="showMessages()">[显示go mod导出进度信息]</a></div>
</body>
</html>
